package cn.butcher.config;

import at.pollux.thymeleaf.shiro.dialect.ShiroDialect;
import cn.butcher.mapper.UserMapper;
import org.apache.catalina.security.SecurityUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

@Configuration
public class ShiroConfig {

    @Autowired
    UserMapper mapper;

    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(@Qualifier("securityManager") DefaultWebSecurityManager manager) {
        ShiroFilterFactoryBean factoryBean = new ShiroFilterFactoryBean();
        factoryBean.setSecurityManager(manager);
        // 这里就是我们设置权限过滤的地方了，当前用户只有拥有我们在这里设置的权限，才能去访问
        Map<String, String> perms = new HashMap<>();

        // 所有请求都需要认证
        perms.put("/**", "authc");
        //authc意思是需要登录认证，而这我们并没有要求说需要具有什么权限或者什么角色才能进

        // 放开静态资源
        perms.put("/css/**", "anon");
        perms.put("/iconfont/**", "anon");
        // 解决未登录是logo图片被拦截的问题
        perms.put("/imgs/logo.jpg", "anon");

        perms.put("/js/**", "anon");
        perms.put("/tools/**", "anon");
        perms.put("/xy-ui/**", "anon");

        // 放开登录请求
        perms.put("/login", "anon");
        perms.put("/toLogin", "anon");

        // 设置需要授权才能访问某个请求
        for (String perm : mapper.getAllPerms()) {
            perms.put(perm, "perms[" + perm + "]");
        }

//        perms.put("/student/look","perms[/student/look]");
//        perms.put("/student/record","perms[/student/record]");

        perms.put("student", "roles[student]");
        perms.put("teacher", "roles[teacher]");
        perms.put("counselor", "roles[counselor]");


        //意思是设置权限，只有拥有/student/**这个权限才能访问，/student/**

        factoryBean.setFilterChainDefinitionMap(perms);

        factoryBean.setLoginUrl("/toLogin");

        factoryBean.setSuccessUrl("/index");

        return factoryBean;
    }

    @Bean
    public DefaultWebSecurityManager securityManager(@Qualifier("userRealm") UserRealm realm) {
        DefaultWebSecurityManager manager = new DefaultWebSecurityManager();
        // 使我们的认证规则生效
        manager.setRealm(realm);
        return manager;
    }

    // 注册到spring中
    // 等于<bean id="userRealm" class="cn.butcher.config.UserRealm "/>
    // xml中bean的id是它的名字，在javaConfig里面，方法名就是bean的名字
    @Bean
    public UserRealm userRealm() {
        return new UserRealm();
    }

    @Bean
    public ShiroDialect shiroDialect() {
        return new ShiroDialect();
    }
}
